<?php

namespace Xin\HttpClient;

use Psr\Http\Message\RequestInterface;
use Xin\Pipeline\PipelineManager;

trait HasInterceptors
{
	/**
	 * @var PipelineManager
	 */
	protected $interceptor;

	/**
	 * 添加请求拦截器
	 * @param callable $callback
	 * @return $this
	 */
	public function addRequestInterceptor($callback)
	{
		$this->interceptor->push($callback, 'requests');

		return $this;
	}

	/**
	 * 移除请求拦截器
	 * @param callable $callback
	 * @return $this
	 */
	public function removeRequestInterceptor($callback)
	{
		$this->interceptor->remove($callback, 'requests');

		return $this;
	}

	/**
	 * 添加响应拦截器
	 * @param callable $callback
	 * @return $this
	 */
	public function addResponseInterceptor($callback)
	{
		$this->interceptor->push($callback, 'responses');

		return $this;
	}

	/**
	 * 移除响应拦截器
	 * @param callable $callback
	 * @return $this
	 */
	public function removeResponseInterceptor($callback)
	{
		$this->interceptor->remove($callback, 'responses');

		return $this;
	}

	/**
	 * 执行请求拦截器
	 *
	 * @param RequestInterface $request
	 * @param array $options
	 * @return array
	 */
	protected function invokeRequestInterceptors(array $options)
	{
		return $this->interceptor->linear($options, 'requests');
	}

	/**
	 * 执行响应拦截器
	 * @param Response $response
	 * @return Response
	 */
	protected function invokeResponseInterceptors(Response $response)
	{
		return $this->interceptor->linear($response, 'responses');
	}
}
